package com.agent.membership.mapper;

import com.agent.membership.entity.CreditAccount;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface CreditAccountMapper extends BaseMapper<CreditAccount> {

    /**
     * 根据用户ID查询积分账户
     * @param userId 用户ID
     * @return 积分账户
     */
    @Select("SELECT * FROM credit_account WHERE user_id = #{userId}")
    CreditAccount selectByUserId(@Param("userId") Long userId);

    /**
     * 增加订阅积分
     * @param userId 用户ID
     * @param amount 增加数量
     * @return 影响行数
     */
    @Update("UPDATE credit_account " +
            "SET total_credits = total_credits + #{amount}, " +
            "subscription_credits = subscription_credits + #{amount} " +
            "WHERE user_id = #{userId}")
    int addSubscriptionCredits(@Param("userId") Long userId, @Param("amount") Integer amount);

    /**
     * 增加奖励积分
     * @param userId
     * @param amount
     * @return
     */
    @Update("UPDATE credit_account " +
            "SET total_credits = total_credits + #{amount}, " +
            "bonus_credits = bonus_credits + #{amount} " +
            "WHERE user_id = #{userId}")
    int addBonusCredits(@Param("userId") Long userId, @Param("amount") Integer amount);

    /**
     * 扣减奖励积分
     * @param userId
     * @param amount
     * @return
     */
    @Update("UPDATE credit_account " +
            "SET bonus_credits = bonus_credits - #{amount} " +
            "WHERE user_id = #{userId} AND bonus_credits >= #{amount}")
    int deductBonusCredits(@Param("userId") Long userId, @Param("amount") Integer amount);

    /**
     * 扣减订阅积分
     * @param userId
     * @param amount
     * @return
     */
    @Update("UPDATE credit_account " +
            "SET subscription_credits = subscription_credits - #{amount} " +
            "WHERE user_id = #{userId} AND subscription_credits >= #{amount}")
    int deductSubscriptionCredits(@Param("userId") Long userId, @Param("amount") Integer amount);

    /**
     * 扣减总积分
     * @param userId
     * @param amount
     * @return
     */
    @Update("UPDATE credit_account " +
            "SET total_credits = total_credits - #{amount} " +
            "WHERE user_id = #{userId} AND total_credits >= #{amount}")
    int deductTotalCredits(@Param("userId") Long userId, @Param("amount") Integer amount);
}